﻿/*	
	stencil - action script 3 isometric game engine.

	http://code.google.com/p/stencilas3/
	
	Copyright (c) 2010 Max Zhuravkov, All Rights Reserved.

	Permission is hereby granted, free of charge, to any person obtaining a copy of
	this software and associated documentation files (the "Software"), to deal in
	the Software without restriction, including without limitation the rights to
	use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
	of the Software, and to permit persons to whom the Software is furnished to do
	so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in all
	copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
	SOFTWARE.
*/
package stencil.core.engine.scene 
{
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.utils.Dictionary;
	import flash.utils.getTimer;
	import stencil.core.engine.events.CameraModelEvent;
	import stencil.core.engine.events.VisibleAreaChangeEvent;
	import stencil.core.engine.events.SceneUpdateEvent;
	import stencil.core.engine.ICameraModel;
	import stencil.core.engine.IGameObject;
	import stencil.core.engine.IGrid;
	import stencil.core.engine.IMapArea;
	import stencil.core.engine.IMapGraph;
	import stencil.core.engine.ISceneObject;
	import stencil.core.engine.ITileSection;
	import stencil.core.engine.Position;
	import stencil.core.engine.TileSettings;
	import stencil.core.errors.ArgumentIsNullError;
	import stencil.core.engine.MapNode;
	import stencil.core.errors.NotImplementedMethodError;
	
	
	/**
	 * A simple scene model implementation which delegates all its methods defined in ISceneStructure 
	 * interface to its <code>data</code> property. 
	 * 
	 * @author Max Zhuravkov
	 */
	public class SimpleSceneModel extends AbstractSceneModel {
		
		protected var flagAreaChanged:Boolean = false;
		
		private var _visibleAreas:Dictionary = new Dictionary();
		
		private var _areaChanged:Dictionary = new Dictionary();
		
		private var _data:ISceneStructure;
		
		private var _objectGrid:IGrid;
		
		//----------------------------------------------------------------
		// Constructor
		//----------------------------------------------------------------
		
		public function SimpleSceneModel(data:ISceneStructure = null) {
			super();
			
			this.data = data;
		}
		
		//----------------------------------------------------------------
		// Public properties
		//----------------------------------------------------------------
		
		/**
		 * The scene data.
		 */
		public function set data(value:ISceneStructure):void {
			if (this._data == value) {
				return;
			}
			this._data = value;
		}
		
		public function get data():ISceneStructure {
			return this._data;
		}
		
		/**
		 * @inheritDoc
		 */
		override public function set objectGrid(value:IGrid):void {
			throw new NotImplementedMethodError("get objectGrid");
		}
		
		override public function get objectGrid():IGrid {
			return this.data.objectGrid;
		}
		
		/**
		 * @inheritDoc
		 */
		override public function set tileGrid(value:IGrid):void {
			throw new NotImplementedMethodError("get tileGrid");
		}
		
		override public function get tileGrid():IGrid {
			return this.data.tileGrid;
		}
		
		/**
		 * @inheritDoc
		 */
		override public function get boundaries():Rectangle { 
			return this.data.boundaries; 
		}
		
		/**
		 * @inheritDoc
		 */
		override public function get globalBoundaries():Rectangle { 
			return this.data.boundaries;  
		}
		
		/**
		 * @inheritDoc
		 */
		override public function set tileSettings(value:TileSettings):void {
			this.data.tileSettings = value;
		}
		
		/**
		 * @inheritDoc
		 */
		override public function get tileSettings():TileSettings {
			return this.data.tileSettings;
		}
		
		/**
		 * @inheritDoc
		 */
		override public function set mapGraph(value:IMapGraph):void {
			this.data.mapGraph = value;
		}
		
		/**
		 * @inheritDoc
		 */
		override public function get mapGraph():IMapGraph {
			return this._data.mapGraph;
		}
		
		/**
		 * @inheritDoc
		 */
		override public function get lists():Array {
			return this.data.lists;
		}
		
		//----------------------------------------------------------------
		// Public methods
		//----------------------------------------------------------------
		
		/**
		 * @inheritDoc
		 */
		override public function getSceneNode(p:Position):ISceneNode {
			return this.data.getSceneNode(p);
		}
		
		/**
		 * @inheritDoc
		 */
		override public function createList(name:String, filter:Function = null):Array {
			return this.data.createList(name, filter);
		}
		
		/**
		 * @inheritDoc
		 */
		override public function getList(name:String):Array {
			return super.getList(name);
		}
		
		/**
		 * @inheritDoc
		 */
		override public function hasList(name:String):Boolean {
			return this.data.hasList(name);
		}
		
		/**
		 * @inheritDoc
		 */
		override public function removeList(name:String):void {
			this.data.removeList(name);
		}
		
		/**
		 * @inheritDoc
		 */
		override public function removeLists():void {
			this.data.removeLists();
		}
		
		/**
		 * @inheritDoc
		 */
		override public function addObject(object:ISceneObject):Boolean {
			var result:Boolean = this.data.addObject(object);
			
			if (result) {
				this.objectAdded(object);
			}else {
				this.objectRemoved(object)
			}
			
			return result;
		}
		
		/**
		 * @inheritDoc
		 */
		override public function removeObject(object:ISceneObject):Boolean {
			var result:Boolean = this.data.removeObject(object);
			
			if (result) {
				this.objectRemoved(object);
			}
			
			return result;
		}
		
		/**
		 * @inheritDoc
		 */
		override public function updateObject(object:ISceneObject):Boolean {
			var result:Boolean = this.data.updateObject(object);
			
			if (result) {
				this.objectUpdated(object);
			}else {
				this.objectRemoved(object);
			}
			
			return result;
		}
		
		/**
		 * @inheritDoc
		 */
		override public function containsObject(object:ISceneObject):Boolean {
			return this.data.containsObject(object);
		}
		
		/**
		 * @inheritDoc
		 */
		override public function getObjects(rect:Rectangle, filter:Function = null):Array {
			return this.data.getObjects(rect, filter);
		}
		
		/**
		 * @inheritDoc
		 */
		override public function getObject(id:String):ISceneObject {
			return this.data.getObject(id);
		}
		
		
		/**
		 * @inheritDoc
		 */
		override public function getObjectsAt(p:Position, filter:Function = null):Array {
			return this.data.getObjectsAt(p, filter);
		}
		
		/**
		 * @inheritDoc
		 */
		override public function getArea(rect:Rectangle, filter:Function = null):IMapArea {
			return this.data.getArea(rect, filter);
		}
		
		/**
		 * @inheritDoc
		 */
		override public function init():void {
			this.data.init();
		}
		
		/**
		 * @inheritDoc
		 */
		override public function getVisibleArea(camera:ICameraModel):IMapArea {
			return this.visibleAreas[camera];
		}
		
		//----------------------------------------------------------------
		// Protected properties
		//----------------------------------------------------------------
		
		protected final function get visibleAreas():Dictionary {
			return this._visibleAreas;
		}
		
		protected final function get areaChanged():Dictionary {
			return this._areaChanged;
		}
		
		//----------------------------------------------------------------
		// Protected methods
		//----------------------------------------------------------------
		
		override protected function cameraAttached(camera:ICameraModel):void {
			
		}
		
		override protected function cameraDetached(camera:ICameraModel):void {
			delete this._visibleAreas[camera];
			delete this._areaChanged[camera];
			
			
		}
		
		protected function objectAdded(o:ISceneObject):void {
			if (o is ITileSection) {
				return;
			}
			
			this.objectUpdated(o);
			
			this.dispatchEvent(new SceneUpdateEvent(SceneUpdateEvent.STN_ADD_OBJECT, o));
		}
		
		protected function objectUpdated(o:ISceneObject):void {
			if (o is ITileSection) {
				return;
			}
			
			for each(var area:IMapArea in this.visibleAreas) {
				var index:int = area.objects.indexOf(o);
				var intersects:Boolean = area.rect.intersects(o.bounds.rect);
				if (index == -1) {
					if(intersects){
						area.objects.push(o);
					}
				}else {
					if (!intersects) {
						area.objects.splice(index, 1);
					}
				}
			}
		}
		
		protected function objectRemoved(o:ISceneObject):void {
			if (o is ITileSection) {
				return;
			}
			
			for each(var area:IMapArea in this.visibleAreas) {
				var index:int = area.objects.indexOf(o);
				if (index != -1) {
					area.objects.splice(index, 1);
				}
			}
			
			this.dispatchEvent(new SceneUpdateEvent(SceneUpdateEvent.STN_REMOVE_OBJECT, o));
		}
		
		override protected function updateScene(time:Number):void {
			
			this.updateChildren(time);
			
			for each(var camera:ICameraModel in this.cameras) {
				var changed:Boolean = camera.update(time);
				if (changed) {
					this.visibleAreaChanged(camera);
				}
				camera.updatePosition(this._areaChanged[camera] ? true : false);
				this._areaChanged[camera] = false;
			}
		}
		
		protected function visibleAreaChanged(camera:ICameraModel):void {
			var visibleArea:Rectangle = camera.visibleArea.clone();
			
			//trace(visibleArea)
			
			if (visibleArea.x % 1 != 0 || visibleArea.y % 1 != 0) {
				return;
			}
			
			var currentArea:IMapArea = this.getVisibleArea(camera);
			var extraSpace:Rectangle = camera.extraSpace;
			var dw:Number = extraSpace ? extraSpace.width : 0;
			var dh:Number = extraSpace ? extraSpace.height : 0;
			
			visibleArea.x -= dw/2;
			visibleArea.y -= dh/2;
			visibleArea.width += dw;
			visibleArea.height += dh;
			
			if (currentArea == null) {
				this.changeVisibleArea(camera, visibleArea, null);
			}else {
				var topLeft:Point = currentArea.rect.topLeft;
				var bottomRight:Point = currentArea.rect.bottomRight;
				var dx:Number = topLeft.x - visibleArea.x;
				var dy:Number = topLeft.y - visibleArea.y;
				var topLeftDistance:Number = Math.sqrt(dx * dx + dy * dy);
				
				dx = bottomRight.x - visibleArea.bottomRight.x;
				dy = bottomRight.y - visibleArea.bottomRight.y;
				
				var bottomRightDistance:Number = Math.sqrt(dx * dx + dy * dy);
				
				if (topLeftDistance >= 10 || bottomRightDistance >= 10) {
					
					this.changeVisibleArea(camera, visibleArea, currentArea.rect);
				}
			}
		}
		
		protected function updateChildren(time:Number):void {
			
		}
		
		protected function changeVisibleArea(camera:ICameraModel, rect:Rectangle, previousRect:Rectangle):void {
			var t:Number = getTimer();
			var area:IMapArea = null;
			
			if (previousRect && Math.abs(rect.x - previousRect.x) < rect.width / 3 && Math.abs(rect.y - previousRect.y) < rect.height / 3) {
				area = this.data.getArea(rect);
				
				var previousArea:IMapArea = this.visibleAreas[camera];
				var previousSections:Array = previousArea.sections;
				var sections:Array = area.sections;
				
				if (previousSections.length == sections.length ) {
					
					var changed:Boolean = false;
					for each(var section:ITileSection in previousSections) {
						if (sections.indexOf(section) == -1) {
							changed = true;
							break;
						}
					}
					
					if (!changed) {
						return;
					}
				}
			}
			
			if (!area) {
				area = this.data.getArea(rect);
			}
			
			this.areaChanged[camera] = true;
			this.visibleAreas[camera] = area;
			camera.grid.redraw(area.nodes, null);
			
			t = getTimer() - t;
			
			
			
			if (t > 0) {
				//trace("getArea " + rect + " took " + t  +" ms.");
			}
			
			this.dispatchEvent(new VisibleAreaChangeEvent(VisibleAreaChangeEvent.STN_VISIBLE_AREA_CHANGE, camera, area));
		}
		
	}

}